<?php
namespace app\ais\controller\api\v1;
use app\ais\controller\api\Base;
use app\ais\model\AisConfig;
use app\ais\model\AisCouponUser;
use app\ais\model\AisStore;
use app\ais\model\AisStoreBill;
use app\ais\model\AisStoreGroup;
use app\ais\model\AisStoreUnion;
use filter\Filter;
use think\Db;

class Gmgroup extends Base{

    protected $store;
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
        $this->store = AisStore::manageStore($this->user->id);
        if(empty($this->store)){
            exit(json_encode(['code' => 403,'msg'=>'无法找到该商家']));
        }
    }

    /**
     * 我的商圈
     * @return void
     */
    public function index(){
        $this->apiSign();
        $flag = [];
        $list = AisStoreGroup::whereIn('id',AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id'=> $this->store->id,'type' => 0])->column('group_id'))->select()->toArray();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['red']       = 0;
                $list[$key]['is_manage'] = 0; 
                if($value['uid'] == $this->user->id){
                    $list[$key]['is_manage'] = 1; 
                    $unionList = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $value['id'] ,'type' => 1])->select();
                    if(!$unionList->isEmpty()){
                        $list[$key]['red'] = count($unionList); //如果有值 代表你是圈主,有n个人待审核
                    }
                }
                $list[$key]['num'] = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $value['id'] ,'type' => 0])->count();
                $flag[] = $list[$key]['is_manage'];
            }
        }
        array_multisort($flag,SORT_DESC,$list); //排序把圈主排在第一
        //申请待通过
        $apply = AisStoreGroup::whereIn('id',AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id'=> $this->store->id ?? 0,'type' => 1])->column('group_id'))->select();
        return enjson(200,'success',['list' => $list,'apply' => $apply]);
    }

    //创建和更新商圈
    public function edit(){
        $param['title']     = $this->request->param('title/s');
        $param['content']   = $this->request->param('content/s');
        $param['face']      = $this->request->param('face/s','[]','htmlspecialchars_decode');
        $this->apiSign($param);
        $validate = $this->validate($param,'Group.edit');
        if(true !== $validate){
            return enjson(403,$validate);
        }
        $face  = Filter::filter_escape(json_decode($param['face'],true));
        $store = AisStore::manageStore($this->user->id);
        if (!$store) {
            return enjson(403,'你不是商家,禁止创建商圈');
        }
        $result = AisStoreGroup::where(['member_miniapp_id' => $this->miniapp_id,'uid' =>  $this->user->id])->find();
        if($result){
            $days = intval((time()-$result->update_time)/86400);
            if($days < 1){
                return enjson(403,'每天只能修改一次商圈信息');
            }
            $result->title       = $param['title'];
            $result->content     = $param['content'];
            $result->update_time = time();
            if(!empty($face)){
                $result->face = $face[0];
            }
            $result->save();
            return enjson(200,'商圈修改成功');
        }else{
            $data['member_miniapp_id'] = $this->miniapp_id;
            $data['uid']               = $this->user->id;
            $data['title']             = $param['title'];
            $data['content']           = $param['content'];
            if(!empty($face)){
                $data['face'] = $face[0];
            }
            $group = AisStoreGroup::create($data);
            AisStoreUnion::create(['member_miniapp_id' => $this->miniapp_id,'group_id' => $group->id,'store_id' => $store->id,'type' => 0,'create_time' => time(),'update_time' => time()]);
            return enjson(200,'商圈创建成功');
        }
    }
   
    //商圈详情
    public function read(){
        $param['id'] = $this->request->param('id');    //商圈id
        $this->apiSign($param);
        $info = AisStoreGroup::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id']])->find();
        if (!$info) {
            return enjson(204);
        }
        $info->is_manage = $info->uid == $this->user->id?1:0;
        $info->red = 0;
        $info->num = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $info->id,'type' => 0])->count();
        if($info->is_manage){
            $info->red = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $info->id,'type' => 1])->count();
        } 
        //买单
        $order = AisStoreBill::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('store_id',AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => 0])->column('store_id'))->sum('money');
        //次数
        $count = AisCouponUser::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('store_id',AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => 0])->column('store_id'))->count();
        //互助
        $help = AisCouponUser::where(['member_miniapp_id' => $this->miniapp_id,'is_end' => 1])->where('','EXP',Db::raw("FIND_IN_SET(".$param['id'].",group_ids)"))->count();
        return enjson(200,['group' => $info,'order' => $order,'count' => $count,'help' => $help]);
    }

    //商圈中的店铺
    public function store(){
        $param['id']   = $this->request->param('id');    //商圈id
        $param['type'] = $this->request->param('type');  //0正常 1待审核 2拒绝 3退出 4踢出
        $this->apiSign($param);
        $list = AisStore::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('id',AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => $param['type']])->column('store_id'))->select();
        if ($list->isEmpty()) {
            return enjson(200);
        }
        return enjson(200,$list);
    }

    //申请加入商圈
    public function add(){
        $param['id'] = $this->request->param('id');  //商圈id
        $this->apiSign($param);
        $store = AisStore::where(['member_miniapp_id' => $this->miniapp_id,'manage_uid' => $this->user->id])->find();
        if(empty($store)){
            return enjson(403,'你不是商家,禁止加入商家');
        }
        $info = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'store_id' => $store->id,'type' => 0])->find();
        if($info){
            return enjson(403,'您已经加入该商圈');
        }
        $info = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'store_id' => $store->id,'type' => 1])->find();
        if($info){
            return enjson(403,'您已经申请过该商圈');
        }
        $config = AisConfig::getConfig($this->miniapp_id);
        $list = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => 0])->select();
        if(!empty($config->group_member) && count($list) >= $config->group_member){
            return enjson(403,'商圈只能有'.$config->group_member.'个成员');
        }
        $size = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $store->id,'type' => 0])->select();
        if(!empty($config->group_join) && count($size) >= $config->group_join){
            return enjson(403,'只能加入'.$config->group_join.'个商圈');
        }
        $code = AisStoreUnion::create(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'store_id' => $store->id,'type' => 1,'create_time' => time(),'update_time' => time()]);
        if ($code) {
            return enjson(200,"已提交申请");
        }
        return enjson(204,'未找到商圈');
    }

    //商圈操作 0同意 2拒绝 3退出 4踢出
    public function operate(){
        $param['group_id']  = $this->request->param('group_id');    //商圈ID
        $param['store_id']  = $this->request->param('store_id',0);  //商店ID
        $param['type']      = $this->request->param('type',1);      //0同意 2拒绝 3退出 4踢出
        $this->apiSign($param);
        //读取商店信息
        if($param['store_id']){
            $condition['id'] = $param['store_id'];
        }else{
            $condition['manage_uid'] = $this->user->id;
        }
        $store = AisStore::where(['member_miniapp_id' => $this->miniapp_id])->where($condition)->find();
        if(empty($store)){
            return enjson(403,'你不是商家');
        }
        $info = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['group_id'],'store_id' => $store->id])->find();
        if(empty($info)){
            return enjson(403,'你不在当前商圈');
        }
        $group = AisStoreGroup::where(['member_miniapp_id' => $this->miniapp_id,'id' => $info->group_id])->find();
        if(!empty($group) && $group->uid == $this->user->id && ($param['type'] == 0 || $param['type'] == 2 || $param['type'] == 4)){
            switch ($param['type']) {
                case 0:
                    //默认通过
                    $info->type = 0;
                    $msg = '已审核通过';
                    //判断权限
                    $config = AisConfig::getConfig($this->miniapp_id);
                    $store_group_num   = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $info->group_id,'type' => 0])->count();
                    if(!empty($config->group_member) && $store_group_num >= $config->group_member){
                        $info->type = 2;
                        $msg = '你的商圈只能有'.$config->group_member.'个成员';
                    }
                    $size = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $store->id,'type' => 0])->count();
                    if(!empty($config->group_join) && $size >= $config->group_join){
                        $info->type = 2;
                        $msg = '已加入'.$size.'个商圈,每个商家只能加入.'.$config->group_join.'个商圈';
                    }
                    break;
                case 2:
                    $info->type = 2;
                    $msg = '已拒绝加圈申请';
                    break;
                case 4:  
                    $info->type = 4;
                    $msg = '已成功踢出我的商圈';
                    break;
                default:
                    return enjson(403,'操作失败');
                    break;
            }
        }elseif($param['type'] == 3){
            $info->type = 3;
            $msg = '你成功退出商圈';
        }else{
            return enjson(403,'操作失败');
        }
        $info->save();
        return enjson(200,$msg);
    }
}